package cn.com.infcn.monitor.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class IFCDateUtils {

	/**
	 * 查询两日期之间所有的天数，闭区间
	 * 
	 * @param startDayStr
	 * @param endDayStr
	 * @param format
	 *            日期格式，输入和返回的日期格式
	 * @return
	 */
	public static List<String> getDaysBetween(String startDayStr, String endDayStr, String format) {
		DateFormat FORMATTER = new SimpleDateFormat(format);

		Calendar startDay = Calendar.getInstance();
		Calendar endDay = Calendar.getInstance();

		try {
			startDay.setTime(FORMATTER.parse(startDayStr));
			endDay.setTime(FORMATTER.parse(endDayStr));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return getDaysBetween(startDay, endDay, format);
	}

	/**
	 * 查询两日期之间所有的天数，闭区间
	 * 
	 * @param startDay
	 * @param endDay
	 * @param format
	 *            返回的日期格式
	 * @return
	 */
	public static List<String> getDaysBetween(Calendar startDay, Calendar endDay, String format) {
		DateFormat FORMATTER = new SimpleDateFormat(format);
		List<String> list = new ArrayList<String>();
		// 给出的日期开始日比终了日大则不执行打印
		if (startDay.compareTo(endDay) > 0) {
			return list;
		}
		// 现在打印中的日期
		Calendar currentPrintDay = startDay;
		list.add(FORMATTER.format(currentPrintDay.getTime()));
		while (true) {
			// 日期加一
			currentPrintDay.add(Calendar.DATE, 1);
			// 日期加一后判断是否达到终了日，达到则终止打印
			if (currentPrintDay.compareTo(endDay) > 0) {
				break;
			}
			// 打印日期
			list.add(FORMATTER.format(currentPrintDay.getTime()));
		}
		return list;
	}

	/**
	 * 获取当前时间距离下一分钟的毫秒数
	 * 
	 * @return
	 */
	public static long getNextMinIntervalMs() {
		Calendar cal = Calendar.getInstance();
		long begin = cal.getTimeInMillis();
		cal.add(Calendar.MINUTE, 1);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		long after = cal.getTimeInMillis();
		return after - begin;
	}

	/**
	 * 获取指定格式的日期字符串
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static String getDateStr(Date date, String format) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 获取指定格式的日期字符串
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static Date parseDate(String dateStr, String format) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.parse(dateStr);
		} catch (Exception e) {
		}
		return null;
	}

	public static void main(String[] args) throws ParseException {
		List<String> list = getDaysBetween("20100202", "20100203", "yyyyMMdd");
		System.out.println(list);
	}
}
